package com.lin.cloud.disk.shiro.realm;

import com.lin.cloud.disk.entity.pojo.User;
import com.lin.cloud.disk.entity.request.LoginRequest;
import com.lin.cloud.disk.service.IUserService;
import com.lin.cloud.disk.shiro.pojo.UserShiroLogin;
import com.lin.cloud.disk.shiro.utils.SHA256Util;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;

/**
 * @author ljc
 * @date 2020/12/10 17:00
 */
@Slf4j
public class DBRealm extends AuthorizingRealm {


    @Resource
    private IUserService userService;


    /**
     *
     *    多重写一个support
     *   标识这个Realm是专门用来验证UsernamePasswordToken
     *   负责验证(UsernamePasswordToken)
     * @param token
     * @return
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        //这个token就是从过滤器中传入的jwtToken
        return token instanceof UserShiroLogin;
    }

    /**
     * 授权权限
     * @Author Sans
     * @CreateTime 2019/6/12 11:44
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        log.info("DBRealm AuthorizationInfo");

        return null;
    }

    /**
     * * 身份认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {


        UserShiroLogin userShiroLogin = (UserShiroLogin)authenticationToken;
        // 1. 获取账号密码
//        String userName = authenticationToken.getPrincipal().toString();
//        String password = new String((char[]) authenticationToken.getCredentials());
        String userName = userShiroLogin.getUserName();
        String password = userShiroLogin.getPassword();
        Long companyId = userShiroLogin.getCompanyId();


        log.info("账号{}",userName);
        log.info("密码{}",password);

        // 2. 求加密后的密码
        String newPassword = SHA256Util.sha256(password,userName);

        log.info("新密码{}",newPassword);

        LoginRequest loginRequest = new LoginRequest();
        loginRequest.setUserName(userName);
        loginRequest.setPassword(newPassword);
        loginRequest.setCompanyId(companyId);
        // 3. 数据库查询
        User user =  userService.getUserByUserNameAndPassword(loginRequest);

        // 4. 比对
        if(null != user){
            log.info("获取到该账号");
            SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user.getUsername(),user.getPassword(), ByteSource.Util.bytes(user.getUsername()),getName());
            return authenticationInfo;
        }

        return null;
    }
}